<template>
	<div class="">
		<el-form :model="ruleForm" ref="ruleForm" :rules="rules" :label-position="labelPosition" label-width="150px" class="demo-ruleForm container">
		  <el-page-header @back="backPage" content="客户信息">
		  </el-page-header>
		    <div class="" style="margin-top:20px">
		        <el-row >
		            <el-col >
		                <el-form-item label="客户：" >
		                   <template>
		                       <el-select
		                           v-model="ruleForm.clientName"
								   @change="chooseCustomer"
								   value-key="id"
		                           style="width:300px"
		                           placeholder="请选择"
		                       >
		                           <el-option
		                               v-for="item in customerList"
		                               :key="item.id"
		                               :label="item.clientName"
		                               :value="item"
		                           ></el-option>
		                       </el-select>
		                   </template>  
		                </el-form-item>
		            </el-col>     
					<el-col :span="10">
					    <el-form-item label="联系人：">
					        <el-input v-model="ruleForm.consignee" placeholder="请输入内容"  style="width:300px">
					        </el-input>  
					    </el-form-item>
					</el-col>
					<el-col :span="12">
					    <el-form-item label="联系方式：">
					        <el-input v-model="ruleForm.phone" placeholder="请输入内容"  style="width:300px">
					        </el-input>  
					    </el-form-item>
					</el-col>
					<el-col >
					    <el-form-item label="详细地址：">
					        <el-input v-model="ruleForm.address" placeholder="请输入内容"  style="width:300px">
					        </el-input>  
					    </el-form-item>
					</el-col> 
					 <el-col :span="10">
					     <el-form-item label="订单来源：">
					        <template>
					            <el-select
									v-model="ruleForm.source"
					                style="width:300px"
					                placeholder="请选择"
					            >
					                <el-option
					                    v-for="item in list"
					                    :key="item.value"
					                    :label="item.value"
					                    :value="item.value"
					                ></el-option>
					            </el-select>
					        </template>  
					     </el-form-item>
					 </el-col>
					 <el-col :span="12">
					     <el-form-item label="交货日期：">
					         <el-date-picker
					             v-model="ruleForm.deliverTime"
					             type="date"
					             value-format="yyyy-MM-dd"
					             placeholder="请选择"
					             style="width:300px"
					         ></el-date-picker>
					     </el-form-item>
					 </el-col>
					 <el-col >
					     <el-form-item label="销售员：">
					         <template>
					             <el-select
								 	 v-model="ruleForm.salesperson"
								 	 @change="chooseSalesman"
									 value-key="id"
					                 style="width:300px"
					                 placeholder="请选择"
					             >
					                 <el-option
					                     v-for="item in userList"
					                     :key="item.id"
					                     :label="item.name"
					                     :value="item"
					                 ></el-option>
					             </el-select>
					         </template>  
					     </el-form-item>
					 </el-col> 
		        </el-row>
		    </div>  
		    <el-form-item class="footerFixed" label-width="0px">
		        <el-button type="primary" @click="submitrule('ruleForm')">提交</el-button>
		        <el-button @click="backPage">返回</el-button>
		    </el-form-item>
		
		</el-form>
		
		<div class="container" style="margin-top:20px;">
			<h3 style="margin-bottom:20px;">订单明细</h3>
			<el-table
			    :data="ruleForm.orderDetailList"
			    border
			    style="margin-top:20px;"
			    ref="multipleTable"
				:summary-method="getSummaries"
				show-summary
			    header-cell-class-name="table-header"
			>
			    <el-table-column prop="name" sortable label="产品标题"></el-table-column>
			    <el-table-column prop="price" sortable label="价格(元)">
					<template slot-scope ="scope">
						<el-input style="width:150px;" v-model="scope.row.price" @change="handleChange(scope.$index, scope.row)"></el-input>   元
					</template>
				</el-table-column>
				<el-table-column prop="number" sortable label="数量">
					<template slot-scope="scope">
						<el-input-number v-model="scope.row.number" controls-position="right" @change="handleChange(scope.$index, scope.row)" :min="1" ></el-input-number>
					</template>
				</el-table-column>
			    <el-table-column prop="totalPrice" sortable label="小计(元)"></el-table-column>
			    <el-table-column label="操作" width="150" align="center">
			        <template slot-scope="scope">
			            <el-button
			                type="text"
			            	style="color: red;"
			                @click="handleDelete(scope.$index, scope.row)"
			            >删除</el-button>
			        </template>
			    </el-table-column>
			</el-table>
			<el-button style="margin-top:10px;" @click="addproducts">+添加产品</el-button>
		</div>
		<el-form :model="data" ref="ruleForm" :rules="rules" :label-position="labelPosition" label-width="150px" style="margin-top: 20px;" class="demo-ruleForm container">
		    <div class="" style="margin-top:20px">
				<el-row  style="margin:20px 0 30px 0px;">
				    <h3 style="margin-bottom:20px;">财务信息</h3>
				    <el-col :span="12">
				        <el-form-item label="发票信息：">
				            <el-select v-model="ruleForm.invoiceType" @change="handleShow" placeholder="请选择" style="width:300px;">
				                <el-option :label="v" :value="v" v-for="(v,i) in fapiaos" :key="i"></el-option>
				            </el-select>  
				        </el-form-item>
				        <el-form-item v-show="showFormItem == 1 || showFormItem == 2" label="纳税人识别号：">
				            <el-input placeholder="请输入内容" v-model="ruleForm.taxpayerNumber"  style="width:300px"></el-input>
				        </el-form-item>
				        <el-form-item v-show="showFormItem == 2" label="开户银行：">
				            <el-input placeholder="请输入内容" v-model="ruleForm.bank"  style="width:300px"></el-input>
				        </el-form-item>
				        <el-form-item v-show="showFormItem == 2" label="付款情况：">
				            <el-select v-model="ruleForm.isPay" placeholder="请选择" style="width:300px;">
				                <el-option :label="v" :value="v" v-for="(v,i) in pays" :key="i"></el-option>
				            </el-select>
				        </el-form-item>
				        <el-form-item v-show="showFormItem == 2" label="付款金额：">
				            <el-input placeholder="请输入内容" style="width:300px;" v-model="ruleForm.payAmount"></el-input>
				        </el-form-item>
				    </el-col>
				    <el-col :span="10">
				        <el-form-item v-show="showFormItem == 1 || showFormItem == 2" label="公司名称：">
				            <el-input placeholder="请输入内容" style="width:300px;" v-model="ruleForm.company"></el-input>
				        </el-form-item>
				        
				        <el-form-item v-show="showFormItem == 2" label="开户名称：">
				            <el-input placeholder="请输入内容" style="width:300px;" v-model="ruleForm.accountName"></el-input>
				        </el-form-item>
				        <el-form-item v-show="showFormItem == 2" label="银行账号：">
				            <el-input placeholder="请输入内容" style="width:300px;" v-model="ruleForm.bankAccount"></el-input>
				        </el-form-item>
				        <el-form-item v-show="showFormItem == 2" label="付款方式：">
				          <el-select v-model="ruleForm.payType" placeholder="请选择" style="width:300px;">
				              <el-option :label="v" :value="v" v-for="(v,i) in paytypes" :key="i"></el-option>
				          </el-select>  
				        </el-form-item>
				    </el-col>
				</el-row>
		    </div>  
			<el-dialog title="选择产品" :visible.sync="dialogTableVisible1">
				<el-table
				    :data="tableData1"
				    border
				    style="margin-top:20px;"
				    ref="multipleTable"
				    header-cell-class-name="table-header"
				>
				    <el-table-column prop="title" sortable label="产品标题"></el-table-column>
				    <!-- <el-table-column prop="createTime" sortable label="添加时间"></el-table-column> -->
				    <el-table-column prop="relatedProducts" sortable label="关联产品"></el-table-column>
					<el-table-column prop="quality" sortable label="保质期">
						<template slot-scope="scope">
							{{scope.row.quality}}月
						</template>
					</el-table-column>
				    <el-table-column label="操作" width="150" align="center">
				        <template slot-scope="scope">
				            <el-button
				                type="text"
				                @click="handleSelectProductDetails(scope.$index, scope.row)"
				            >选择</el-button>
				        </template>
				    </el-table-column>
				</el-table>
				<el-pagination layout="total, prev, pager, next, jumper" :page-size="pagesize" :current-page.sync="currentPage1"  @current-change="handleCurrentChange1" :total="total1" style="margin-top:20px"></el-pagination>
			  
			</el-dialog>
			
		    <el-form-item class="footerFixed" label-width="0px">
		        <el-button type="primary" @click="submitrule('ruleForm')">提交</el-button>
		        <el-button @click="backPage">返回</el-button>
		    </el-form-item>
		
		</el-form>
	</div>
</template>

<script>
import { order_save,product_findOwnAll,order_update,order_findById } from '@/request/breedApi';
import { user_findByAll,client_findByAll,products_findByList } from '@/request/api';
	export default{
		data(){
			return{
				dialogTableVisible1:false,
				pagesize:10,
				total1:0,
				currentPage1:1,
				fapiaos:["不开发票","增值税普通发票","增值税专用发票"],
				username:'',
				fapiao:'',
				type:'',
				pay:'',
				pays:["未付款","已付款"],
				payType:'',
				paytypes:["现金","银行转账","微信","支付宝"],
				showFormItem:'',
				customer:"",
				salesman:"",
				list:[
					{value:"线下"},
					{value:"淘宝"},
					{value:"京东"},
					{value:"微信"},
					{value:"微店"},
				],
				labelPosition:'right',
				ruleForm:{
					orderDetailList: []
				},
				rules:{},
				tableData:[],
				data:{},
				userList:[],
				customerList:[],
				tableData1:[],
				orderNo: '',
				invoiceId: ''
			}
		},
		mounted(){
			this.id = this.$route.query.id
			this.orderNo = this.$route.query.orderNo
			if(this.id == undefined){
				
			}else{
				this.get()
			}
			this.init();
			this.getproducts()
		},
		methods:{
			get(){
				order_findById(this.id).then((res)=>{
					this.ruleForm = res.data.order
					this.ruleForm.customer = res.data.order.clientName
					this.ruleForm.consignee = res.data.order.consignee
					this.ruleForm.salesperson = res.data.order.salesperson
					this.ruleForm.orderDetailList = res.data.details
					this.invoiceId = res.data.order.invoiceId
					console.log(this.ruleForm.orderDetailList,'4545')
					this.showSH  =true
					
					if(res.data.order.payState == 0){
						this.ruleForm.isPay = '未付款'
					}else if(res.data.order.payState == 1){
						this.ruleForm.isPay = '已付款'
					}else if(res.data.order.payState == 2){
						this.ruleForm.isPay = '已付全款'
					}
					if(res.data.order.invoiceId == 0){
						this.ruleForm.invoiceType = '不开发票'
						this.showFormItem = 0
					}else if(res.data.invoice.type == '1'){
						this.ruleForm.invoiceType = '增值税普通发票'
						this.ruleForm.taxpayerNumber = res.data.invoice.invoiceCode
						this.ruleForm.company = res.data.invoice.invoiceRise
						this.showFormItem = 1
					}else if(res.data.invoice.type == '2'){
						this.ruleForm.invoiceType = '增值税专用发票'
						this.ruleForm.invoiceAddress = res.data.invoice.invoiceAddress
						this.ruleForm.bank = res.data.invoice.invoiceBank
						this.ruleForm.bankAccount = res.data.invoice.invoiceBankCode
						this.ruleForm.taxpayerNumber = res.data.invoice.invoiceCode
						this.ruleForm.accountName = res.data.invoice.invoiceName
						this.ruleForm.invoicePhone = res.data.invoice.invoicePhone
						this.ruleForm.company = res.data.invoice.invoiceRise
						this.ruleForm.payAmount = res.data.order.payAmount
						this.showFormItem = 2
					}
				})
			},
			getSummaries(param) {
				const { columns, data } = param;
				const sums = [];
				let values = []
				columns.forEach((column, index) => {
					if (index === 0) {
						sums[index] = '合计';
						return;
					}
					if(column.property == "totalPrice"){
						values = data.map(item => Number(item.totalPrice))
					}
					if(column.property == "totalPrice") {
						// values = data.map(item => Number)
						sums[index] = values.reduce((prev,curr) => {
							const value = Number(curr)
							if(!isNaN(value)){
								this.totalAmount = prev + curr
								return prev + curr
							}else{
								return prev
							}
						},0)
						sums[index]
					} else {
						sums[index] = ""
					}
				});
				this.totalMoney = sums[3]
				return sums;
				
			  },
			addproducts(){
				this.dialogTableVisible1 = true
			},
			getproducts(){
				let data = {
					page:this.currentPage1
				}
				products_findByList(data).then((res)=>{
					this.tableData1 = res.rows
					this.total1 = res.total
				})
			},
			handleSelectProductDetails(index,row){

				console.log(111)
				this.ruleForm.orderDetailList.push({
					name:row.title,
					price:'',
					number:'',
					totalPrice:''
				})
				this.dialogTableVisible1 = false
			},
			handleChange(index,row){
				row.totalPrice = row.number*row.price
				// this.getSummaries()
			},
			handleCurrentChange1(val){
				this.currentPage1 = val
				this.getproducts()
			},
			init() {
				user_findByAll("").then((res) => {
					this.userList = res.data;
				});
				client_findByAll("").then((res)=>{
					this.customerList = res.data
				})
				// product_findOwnAll("").then((res)=>{
					
				// })
				
			},
			
			// 列表删除
			handleDelete(index,row){
				this.tableData.splice(index,1)
			},
			backPage(){
				this.$router.go(-1)
			},
			// 提交
			submitrule(){
				// console.log(this.ruleForm);
				// this.ruleForm.orderDetailList = this.tableData
				// this.ruleForm.totalNumber = this.totalNumber
				console.log(this.ruleForm,'1111')


				this.ruleForm.orderDetailedList = this.tableData
				// this.ruleForm.orderDetailedList.name = this.tableData.title
				// this.ruleForm.orderDetailedList.totalAmount = this.tableData.money
				// this.ruleForm.orderDetailedList = this.tableData
				this.ruleForm.deliverState = '0'
				this.ruleForm.totalAmount = this.totalAmount
				this.ruleForm.id = ''
				if(this.ruleForm.invoiceType == '不开发票'){
					this.ruleForm.invoiceId = '0'
				} else {
					this.ruleForm.invoiceId = ''
				}
				// console.log(this.totalAmount,'111')
				const dingdan = {"order": {},"details": [],"invoice": {}}
					dingdan.details = this.ruleForm.orderDetailList
					if(this.id != undefined){
						dingdan.order.id = this.id
					} else {
						dingdan.order.id = ''
					}
					if(this.ruleForm.invoiceType == '增值税普通发票') dingdan.invoice.type = '1'
					if(this.ruleForm.invoiceType == '增值税专用发票') dingdan.invoice.type = '2'
					dingdan.invoice.invoiceRise = this.ruleForm.company
					dingdan.invoice.invoiceCode = this.ruleForm.taxpayerNumber
					dingdan.invoice.invoicePhone = ''
					dingdan.invoice.invoiceAddress = ''
					dingdan.invoice.invoiceName = this.ruleForm.accountName
					dingdan.invoice.invoiceBank = this.ruleForm.bank
					dingdan.invoice.invoiceBankCode = this.ruleForm.bankAccount
					dingdan.invoice.cash = this.ruleForm.totalMoney

					// dingdan.order.id = this.headerlist.id
					if(this.ruleForm.isPay == '未付款') dingdan.order.payState = 0
					if(this.ruleForm.isPay == '已付款') dingdan.order.payState = 1
					if(this.ruleForm.isPay == '已付首款') dingdan.order.payState = 2
					// dingdan.order.payState = this.headerlist.payState
					dingdan.order.deliverState = this.ruleForm.deliverState  
					dingdan.order.clientId = this.ruleForm.customerId
					dingdan.order.clientName = this.ruleForm.clientName
					dingdan.order.deliverTime = this.ruleForm.deliverTime
					dingdan.order.salesperson = this.ruleForm.salesperson
					dingdan.order.source = this.ruleForm.source
					dingdan.order.consignee = this.ruleForm.consignee
					dingdan.order.phone = this.ruleForm.phone
					dingdan.order.address = this.ruleForm.address
					if(this.invoiceId != '' && this.ruleForm.invoiceType != '不开发票') {
						dingdan.order.invoiceId = this.invoiceId
					}else {
						dingdan.order.invoiceId = this.ruleForm.invoiceId
					}
					dingdan.order.payType = this.ruleForm.payType   
					dingdan.order.payAmount = this.ruleForm.payAmount
					if(dingdan.order.payAmount > this.totalAmount){
						this.$notify({
						title: '提示',
						message: '付款金额不得大与总金额',
						type: 'success',
						duration: 1000
						});
						return
					}
					dingdan.order.totalAmount = this.ruleForm.totalAmount

					if(this.orderNo != ''){
						dingdan.order.orderNo = this.orderNo
					} else {
						dingdan.order.orderNo = ''
					}
					dingdan.order.logistics = ''
					dingdan.order.receiveTime = ''
					order_save(dingdan).then((res) => {
						if (res.code == 200) {
							this.$notify({
								title: '提示',
								message: '保存成功',
								type: 'success',
								duration:1000
							});
							this.backPage()
						}
					});
				
			},
			//改变客户时触发
			chooseCustomer(ele) {
				this.ruleForm.customerId = ele.id;
				this.ruleForm.clientName = ele.clientName;
			},
			//改变销售人时触发
			chooseSalesman(ele) {
				this.ruleForm.salesmanId = ele.id;
				this.ruleForm.salesperson = ele.name;
			},
			handleShow(){
				  if(this.ruleForm.invoiceType == '不开发票' || this.ruleForm.invoiceType == null){
					this.showFormItem = 0
				  }else if(this.ruleForm.invoiceType == '增值税普通发票'){
					this.showFormItem = 1
				  }else if(this.ruleForm.invoiceType == '增值税专用发票'){
					this.showFormItem = 2
				  }
			 }
		},
		
	}
</script>

<style scoped>
	.el-pagination{
	    text-align: center;
	}
</style>
